package com.xinyue.game.server.logic.player;

import com.xinyue.game.server.common.EnumGameError;
import com.xinyue.game.server.common.GameServerConfig;
import com.xinyue.game.utils.token.GameToken;
import com.xinyue.game.utils.token.TokenDecodeException;
import com.xinyue.game.utils.token.TokenExpireException;
import com.xinyue.game.utils.token.TokenManager;
import com.xinyue.server.framework.common.GameLogicException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author 王广帅
 * @since 2022/1/5 22:41
 */
@Service
public class UserService {
    @Autowired
    private GameServerConfig gameServerConfig;

    private TokenManager<GameToken> tokenManager;

    @PostConstruct
    public void init() {
        tokenManager = new TokenManager(gameServerConfig.getTokenAesKey());
    }

    /**
     * 检测连接的token是否合法，如果不合法表示非法登陆，断开连接
     *
     * @param userId
     * @param token
     */
    public void checkToken(String userId, String token) {
        GameToken userToken = null;
        try {
            userToken = tokenManager.decodeToken(token, GameToken.class);
        } catch (TokenDecodeException e) {

            throw new GameLogicException(EnumGameError.TOKEN_ERROR, e.getMessage());
        } catch (TokenExpireException e) {
            throw new GameLogicException(EnumGameError.TOKEN_EXPIRE, e.getMessage());
        }
        if (!userId.equals(userToken.getUserId())) {
            throw new GameLogicException(EnumGameError.TOKEN_ERROR, "userId不一致");
        }
    }

    public static void checkUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            throw new GameLogicException(EnumGameError.USER_ID_ERROR, "userId不能为空");
        }
        if (userId.length() > 64) {
            throw new GameLogicException(EnumGameError.USER_ID_ERROR, "用户Id非法");
        }
    }
}
